package com.yuanheng100.ems4j.service.handler;

import com.yuanheng100.ems4j.common.constant.UseStatus;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by wangguangshuo on 2016/12/16.
 */
public class UseStatusTypeHandler implements TypeHandler<UseStatus>
{
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, UseStatus useStatus, JdbcType jdbcType) throws SQLException
    {
        if (useStatus != null)
        {
            preparedStatement.setShort(i, useStatus.code);
        } else
        {
            preparedStatement.setObject(i, UseStatus.ABLE.code);
        }
    }

    @Override
    public UseStatus getResult(ResultSet resultSet, String s) throws SQLException
    {
        Short code = resultSet.getShort(s);
        return getStatus(code);
    }

    @Override
    public UseStatus getResult(ResultSet resultSet, int i) throws SQLException
    {
        Short code = resultSet.getShort(i);
        return getStatus(code);
    }

    @Override
    public UseStatus getResult(CallableStatement callableStatement, int i) throws SQLException
    {
        Short code = callableStatement.getShort(i);
        return getStatus(code);
    }

    private UseStatus getStatus(Short code)
    {
        if (code != null)
        {
            return UseStatus.statusMap.get(code);
        }
        return null;
    }
}
